package com.example.zyl.common.config;

import com.example.zyl.common.enums.RedisQueueEnum;
import com.example.zyl.common.listener.RedisDelayedQueueListener;
import com.example.zyl.common.query.query.RedisQueueMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Component
@Slf4j
public class RedisDelayedQueueInit {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisDelayedQueueListener<RedisQueueMessage> queueListener;

    @Resource
    @Qualifier("threadScheduledExecutor")
    private ThreadPoolTaskExecutor executors;


    @Scheduled(fixedDelay = 5000)  // 每5秒检查一次
    public void checkQueue() {
        RedisQueueEnum[] values = RedisQueueEnum.values();
        for (RedisQueueEnum value : values) {
            executors.submit(() -> {
                try {
                    String queueName = value.getQueueName();
                    log.info("检查队列 ===> [{}]", queueName);
                    RBlockingQueue<?> blockingQueue = redissonClient.getBlockingQueue(queueName);
                    Object poll = blockingQueue.poll();
                    if (poll != null) {
                        StopWatch stopWatch = new StopWatch();
                        stopWatch.start();
                        log.info("队列 ===> [{}] 有任务，开始计时处理, 当前时间 ===> [{}]", queueName, LocalDateTime.now());
                        RedisQueueMessage message = new RedisQueueMessage();
                        message.setQueueEnum(value);
                        message.setMessage(poll);
                        queueListener.invoke(message);
                        stopWatch.stop();
                        log.info("队列 ===> [{}] 处理任务完成, 耗时 ===> [{}] ms", queueName, stopWatch.getTime());
                    }
                } catch (Exception e) {
                    log.error("处理任务时出现错误 ===> [{}]", e.getMessage(), e);
                }
            });
        }
    }
}
